<template>
  <div>
    <el-container>
      <el-main v-loading="!booksAvailable" element-loading-text="拼命加载中">
        <el-collapse v-model="activeName">
          <el-collapse-item title="我上传的" name="1">
            <el-row class="cardStyle">
              <el-col style=" margin: 0 20px 20px 0;" :span="4" v-for="(item, index) in books.upload" :key="index"  >
                <el-card  :body-style="{ padding: '0px' }" style="width: 93%">
                  <div @click="readingTheBook(index, 'u')">
                    <img  :src="item.coverUrl" class="image">
                  </div>
                  <div style="padding: 14px;">
                    <el-rate disabled v-model="item.grade"></el-rate>
                    <div class="bottom clearfix">
                      <el-row :gutter="20">
                        <el-col :span="18"><span style="font-size: 12px;">{{ item.name }}</span></el-col>
                        <el-col :span="6">
                          <el-dropdown trigger="click">
                            <span class="el-dropdown-link"><i class="el-icon-arrow-down el-icon--right"></i></span>
                            <el-dropdown-menu slot="dropdown">
                              <el-dropdown-item @click.native="toConfirm(item.id, 'u')" icon="el-icon-delete" >删除</el-dropdown-item>
                              <el-dropdown-item @click.native="toFrum(item.literatureId)" icon="el-icon-chat-line-square">讨论区</el-dropdown-item>
                            </el-dropdown-menu>
                          </el-dropdown>
                        </el-col>
                      </el-row>
                    </div>
                  </div>
                </el-card>
              </el-col>
              <el-col style=" margin: 0 20px 20px 0;" :span="4" >
                <el-card  style="border: 2px dashed #B3C0D1;width: 93%">
                  <br/>
                  <br/>
                  <br/>
                  <br/>
                  <el-tooltip class="item" effect="dark" content="点我上传" placement="bottom-start">
                    <el-button @click="dialogFormVisible = true"  icon="el-icon-plus"></el-button>
                  </el-tooltip>
                  <br/>
                  <br/>
                  <div>上传文献</div>
                  <br/>
                  <br/>
                </el-card>
              </el-col>
            </el-row>
          </el-collapse-item>
          <el-collapse-item title="我阅读的" name="2">
            <h1 v-if="books.reading.length===0">当前您没有阅读文献</h1>
            <el-row class="cardStyle" v-if="books.reading.length!==0">
              <el-col style=" margin: 0 20px 20px 0;" :span="4" v-for="(item, index) in books.reading" :key="index" >
                <el-card  :body-style="{ padding: '0px' }" >
                  <div @click="readingTheBook(index, 'r')">
                    <img :src="item.coverUrl" class="image">
                  </div>
                  <div style="padding: 14px;">
                    <el-rate disabled v-model="item.grade"></el-rate>
                    <div class="bottom clearfix">
                      <el-row :gutter="20">
                        <el-col :span="18"><span style="font-size: 12px;text-align: justify">{{ item.name }}</span></el-col>
                        <el-col :span="6">
                          <el-button @click="showComfirmDialog(item.progressId)" type="danger" icon="el-icon-delete" class="button"></el-button>
                        </el-col>
                      </el-row>
                    </div>
                  </div>
                </el-card>
              </el-col>
            </el-row>
          </el-collapse-item>
        </el-collapse>
      </el-main>
    </el-container>
    <!--上传文献的对话框-->
    <el-dialog title="上传文献" v-loading="dialogLoading" :visible.sync="dialogFormVisible" width="30%">
      <el-form :model="uploadForm" :rules="uploadFormRules" ref="uploadFormRules" enctype="multipart/form-data">
        <el-form-item prop="file" label="文件">
          <el-upload
            class="upload-demo"
            ref="upload_epub"
            :limit="1"
            action="#"
            :http-request="httpRequestUploadFile"
            :before-upload="beforeUpload"
            accept="application/epub"
            v-model="uploadForm.file"
            :file-list="fileList">
            <el-button size="default" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传1个.epub文件</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="文献类别" label-width="100px" prop="category">
          <el-select v-model="uploadForm.category" placeholder="请选择">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="resetForm('uploadFormRules')">取 消</el-button>
        <el-button type="primary" @click="fileSubmit('uploadFormRules')">确 定</el-button>
      </div>
    </el-dialog>
      <el-dialog
        title="提示"
        :visible.sync="dialogDelete"
        width="30%">
        <span style="font-size: 20px;">确认删除么</span>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogDelete = false">取 消</el-button>
          <el-button type="primary" @click="confirmDelete">确 定</el-button>
       </span>
      </el-dialog>
    <el-dialog
      title="提示"
      :visible.sync="dialogDeleteReadingProgress"
      width="30%">
      <span style="font-size: 20px;">确认不再阅读了吗？</span>
      <span slot="footer" class="dialog-footer">
          <el-button @click="dialogDeleteReadingProgress = false">取 消</el-button>
          <el-button type="primary" @click="deleteReadingProgress">确 定</el-button>
       </span>
    </el-dialog>
  </div>
</template>

<script>
import Epub from 'epubjs'
import {postRequest, postFileRequest, getRequest, deleteRequest} from '../../tools/api'
import {mymessage} from '../../tools/mymessage'

export default {
  name: 'bookshelf',
  data () {
    return {
      bookid: -1,
      dialogDeleteReadingProgress: false,
      dialogFormVisible: false,
      currentDate: new Date(),
      booksAvailable: false,
      dialogLoading: false,
      dialogDelete: false,
      bookIdSelect: -1,
      bookTypeSelect: '',
      options: [{
        value: 0,
        label: '科技图书'
      }, {
        value: 1,
        label: '科技期刊'
      }, {
        value: 2,
        label: '专利文献'
      }, {
        value: 3,
        label: '会议文献'
      }, {
        value: 4,
        label: '科技报告'
      }, {
        value: 5,
        label: '政府出版物'
      }, {
        value: 6,
        label: '学位论文'
      }, {
        value: 7,
        label: '标准文献'
      }, {
        value: 8,
        label: '产品资料'
      }, {
        value: 9,
        label: '其他文献'
      }],
      books: {
        upload: [],
        reading: []
      },
      uploadForm: {
        file: '',
        category: ''
      },
      category: '',
      fileList: [],
      uploadFormRules: {
        file: [{required: true, message: '请上传文件', trigger: 'blur'}],
        category: [{required: true, message: '请选择文献类别', trigger: 'blur'}]
      },
      activeName: '1'
    }
  },
  created () {
    this.initBookShelf()
  },
  methods: {
    showComfirmDialog (bookid) {
      this.dialogDeleteReadingProgress = true
      this.bookid = bookid
    },
    deleteReadingProgress () {
      deleteRequest('/readingprogress/delete/' + this.bookid + '/' + 1).then(res => {
        if (res.code === 200) {
          this.dialogDeleteReadingProgress = false
          mymessage.success('移除成功！')
          this.initBookShelfRead()
        }
      })
    },
    readingTheBook (index, type) {
      // query是使用path来跳转的,params根据name来跳转的
      const URL = type === 'r' ? this.books.reading[index].url : this.books.upload[index].url
      const BOOKID = type === 'r' ? this.books.reading[index].literatureId : this.books.upload[index].id
      this.$router.push({
        path: '/EBook',
        query: {bookUrl: URL, bookId: BOOKID}
      })
    },
    initBookShelf () {
      this.initBookShelfUpload()
      this.initBookShelfRead()
      this.booksAvailable = true
      // console.log('books', this.books)
    },
    initBookShelfUpload () {
      getRequest('/literaturedetail/queryLiteratureGrade/' + this.$store.getters.userInfo.id).then((res) => {
        console.log('initBookShelfUpload :res:', res)
        if (res.code === 200) {
          this.books.upload = res.data
          // 请求文献封面
          for (let i = 0; i < this.books.upload.length; i++) {
            const book = new Epub(this.books.upload[i].url) // 生成Book对象
            book.loaded.cover.then(cover => {
              book.archive.createUrl(cover).then(url => {
                this.books.upload[i].coverUrl = url
                this.$forceUpdate()
              })
            })
            if (this.books.upload[i].name.length > 10) {
              this.books.upload[i].name = this.books.upload[i].name.slice(0, 10) + '...'
            }
          }
        }
      })
    },
    initBookShelfRead () {
      getRequest('/readingprogress/queryIsReading/' + this.$store.getters.userInfo.id).then((res) => {
        console.log('queryIsReading:', res)
        if (res.code === 200) {
          this.books.reading = res.data
          for (let i = 0; i < this.books.reading.length; i++) {
            const book = new Epub(this.books.reading[i].url) // 生成Book对象
            book.loaded.cover.then(cover => {
              book.archive.createUrl(cover).then(url => {
                this.books.reading[i].coverUrl = url
                this.$forceUpdate()
              })
            })
            if (this.books.reading[i].name.length > 10) {
              this.books.reading[i].name = this.books.reading[i].name.slice(0, 10) + '...'
            }
          }
        }
      })
    },
    beforeUpload (file) {
      console.log('file.type:', file.type)
      const isJEpub = file.type === 'application/epub' || file.type === 'application/epub+zip'
      const isLt100M = file.size / 1024 / 1024 < 100

      if (!isJEpub) {
        this.$message.error('上传的文件只能是epub格式')
      }
      if (!isLt100M) {
        this.$message.error('上传头像图片大小不能超过 100MB!')
      }
      return isJEpub && isLt100M
    },
    httpRequestUploadFile (data) {
      this.uploadForm.file = data.file
    },
    fileSubmit (form) {
      this.$refs[form].validate((valid) => {
        if (valid) {
          this.dialogLoading = true
          var formDate = new FormData()
          formDate.append('file', this.uploadForm.file)
          // 先存附件表
          postFileRequest('/attach/upload/literature_detail/0/' + this.uploadForm.category, formDate).then(res => {
            console.log('attach res:', res)
            if (res.code === 200) {
              // 再存文献表
              const literatureInfo = {
                name: this.uploadForm.file.name,
                uploaderId: this.$store.getters.userInfo.id,
                numCode: this.getUniqueID(),
                type: this.uploadForm.category,
                fileId: res.data.id
              }
              postRequest('/literaturedetail/upload', literatureInfo).then(res => {
                console.log('literaturedetail upload res:', res)
                if (res.code === 200) {
                  this.initBookShelfUpload()
                  mymessage.success('上传成功！')
                } else {
                  mymessage.error('上传失败')
                }
              })
              this.dialogLoading = false
              this.fileList = []
              this.resetForm(form)
              //  更新书架
            } else {
              mymessage.error('上传失败')
              this.dialogLoading = false
            }
          })
        }
      })
    },
    resetForm (form) {
      this.fileList = []
      this.dialogFormVisible = false
      this.$refs[form].resetFields()
    },
    getUniqueID () { // 唯一标识符
      var time = Date.now().toString(36) // 当前时间转成 36 进制字符串
      var random = Math.random().toString(36) // 当前随机数转成 36 进制字符串
      random = random.substring(2, random.length) // 去除随机数的 0. 字符串
      return random + time // 返回唯一ID
    },
    toConfirm (bookid, type) {
      this.bookIdSelect = bookid
      this.bookTypeSelect = type
      this.dialogDelete = true
      console.log('bookSelect:', this.bookTypeSelect, this.bookIdSelect)
    },
    confirmDelete () {
      this.dialogDelete = false
      deleteRequest('/literaturedetail/delete/' + this.$store.getters.userInfo.id + '/' + this.bookIdSelect).then(res => {
        console.log('res:', res)
        if (res.code === 200) {
          mymessage.success('删除成功！')
          if (this.bookTypeSelect === 'u') {
            this.initBookShelfUpload()
          } else {
            this.initBookShelfRead()
          }
        }
      })
    },
    toFrum (bookid) {
      this.$router.push({
        path: '/ThemeForum',
        query: {
          id: bookid
        }
      })
    }
  }
}
</script>

<style scoped>
.cardStyle{
  display: flex;
  flex-wrap: wrap;
  justify-content: flex-start;
  align-items: center;
}
.el-header {
  background-color: #B3C0D1;
  color: #333;
  line-height: 60px;
}

.el-aside {
  color: #333;
}

.time {
  font-size: 13px;
  color: #999;
}

.bottom {
  margin-top: 13px;
  line-height: 12px;
}

.button {
  padding: 0;
  float: right;
}

.image {
  width: 100%;
  height: 200px;
  display: block;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}

.clearfix:after {
  clear: both
}

</style>
